<template>
    <AButton
        @click="
            operationType = 'create';
            state.formData = { ...initFormData };
            modalVisible = true;
        "
        type="primary"
        shape="circle"
    >
        <template #icon>
            <PlusOutlined />
        </template>
    </AButton>
    <ATable :pagination="false" :columns="columns" :dataSource="state.dataSource.map((item, index) => ({ ...item, key: index }))">
        <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
                <AButton
                    @click="
                        operationType = 'update';
                        state.formData = {
                            ...record,
                            status: record.status ? true : false,
                            is_super: record.is_super ? true : false,
                        };
                        state.updatedRecord = record;
                        modalVisible = true;
                    "
                    type="primary"
                    >编辑</AButton
                >
                <APopconfirm @confirm="handleDelete(record)" :title="`确定删除${record.username}吗？`">
                    <AButton type="danger">删除</AButton>
                </APopconfirm>
            </template>
        </template>
    </ATable>
    <AModal @ok="confirmForm" v-model:visible="modalVisible" :title="`${operationType === 'create' ? '添加' : '编辑'}`" :width="600">
        <ARow>
            <ACol span="21">
                <AForm @finish="confirmForm" ref="formRef" :model="state.formData" v-bind="{ labelCol: { span: 6 }, wrapperCol: { span: 18 } }">
                    <AFormItem name="username" label="用户名" :rules="[{ required: true, message: '请输入用户名' }]">
                        <AInput v-model:value="state.formData.username" placeholder="请输入用户名" />
                    </AFormItem>
                    <AFormItem name="status" label="用户状态">
                        <ASwitch v-model:checked="state.formData.status" checkedChildren="可用" unCheckedChildren="禁用" />
                    </AFormItem>
                    <AFormItem name="sex" label="性别">
                        <ASelect v-model:value="state.formData.sex">
                            <ASelectOption :value="0">女</ASelectOption>
                            <ASelectOption :value="1">男</ASelectOption>
                            <ASelectOption :value="2">保密</ASelectOption>
                        </ASelect>
                    </AFormItem>
                    <AFormItem name="role_id" label="角色">
                        <ASelect v-model:value="state.formData.role_id">
                            <ASelectOption v-for="(item, index) in state.roleList" :key="index" :value="item._id">{{ item.title }}</ASelectOption>
                        </ASelect>
                    </AFormItem>
                    <AFormItem
                        name="mobile"
                        label="手机号"
                        :rules="[
                            {
                                pattern: /^1[2|3|4|5|7|8][0-9]{9}$/,
                                message: '不符合手机号格式',
                            },
                        ]"
                    >
                        <AInput v-model:value="state.formData.mobile" placeholder="请输入手机号" type="number" :maxlength="11" />
                    </AFormItem>
                    <AFormItem
                        name="email"
                        label="邮箱"
                        :rules="[
                            {
                                pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                message: '不符合邮箱格式',
                            },
                        ]"
                    >
                        <AInput v-model:value="state.formData.email" placeholder="请输入邮箱" />
                    </AFormItem>
                    <AFormItem name="is_super" label="超级管理员">
                        <ASwitch v-model:checked="state.formData.is_super" checkedChildren="是" unCheckedChildren="否" />
                    </AFormItem>
                    <AFormItem label="头像" name="avatar">
                        <CustomUpload v-model:image="state.formData.avatar" />
                    </AFormItem>
                </AForm>
            </ACol>
            <ACol span="3"> </ACol>
        </ARow>
    </AModal>
</template>

<script setup>
import { PlusOutlined } from "@ant-design/icons-vue";
import { reactive, ref, toRefs } from "vue";
import { createUserApi, deleteUserApi, getUserApi, updateUserApi } from "@/api/user";
import { message } from "ant-design-vue";
import { getRoleApi } from "@/api/role";
import CustomUpload from "@/components/CustomUpload";
const columns = [
    {
        dataIndex: "_id",
        title: "ID",
    },
    {
        dataIndex: "username",
        title: "用户名",
    },
    {
        dataIndex: "status",
        title: "状态",
        customRender: ({ text }) => (text ? "可用" : "不可用"),
    },
    {
        dataIndex: "role",
        title: "角色",
        customRender: ({ text }) => (text && text ? text.map(item => item.title).join("、") : ""),
    },
    {
        dataIndex: "sex",
        title: "性别",
        customRender: ({ text }) => (text === 0 ? "女" : text === 1 ? "男" : text === 2 ? "保密" : ""),
    },
    {
        dataIndex: "mobile",
        title: "手机号",
    },
    {
        dataIndex: "email",
        title: "邮箱",
    },
    {
        dataIndex: "is_super",
        title: "超级管理员？",
        customRender: ({ text }) => (text ? "是" : "否"),
    },
    {
        title: "操作",
        dataIndex: "operation",
        fixed: "right",
    },
];
const initFormData = {
    username: "",
    sex: 2,
    status: true,
    role_id: "",
    mobile: null,
    email: "",
    is_super: true,
    avatar: "",
};
const state = reactive({
    dataSource: [],
    formData: { ...initFormData },
    updatedRecord: {},
    roleList: [],
});
const modalVisible = ref(false);
const operationType = ref("create");
const formRef = ref();
const getUser = () => {
    return getUserApi().then(res => {
        if (res.code === 200) {
            state.dataSource = reactive(res.data);
            return res.data;
        }
    });
};
getUser();
const confirmForm = () => {
    formRef.value.validate().then(result => {
        const body = { ...result, status: result.status ? 1 : 0, is_super: result.is_super ? 1 : 0 };
        if (operationType.value === "create") {
            createUserApi(body).then(async res => {
                if (res.code === 200) {
                    await getUser();
                    message.success("添加成功");
                    modalVisible.value = false;
                }
            });
        }
        if (operationType.value === "update") {
            updateUserApi({ _id: state.updatedRecord._id, ...body }).then(async res => {
                if (res.code === 200) {
                    await getUser();
                    message.success("更新成功");
                    modalVisible.value = false;
                }
            });
        }
    });
};
const handleDelete = record => {
    deleteUserApi({ _id: record._id }).then(async res => {
        if (res.code === 200) {
            await getUser();
            message.success("删除成功");
        }
    });
};
const getRole = () => {
    getRoleApi().then(res => {
        if (res.code === 200) {
            state.roleList = res.data;
        }
    });
};
getRole();
</script>

<style scoped lang="scss">
</style>
